 //文章类别相关接口
 const express = require('express')
 const router = express.Router()
 const db = require('../utils/db')



 //获取所有文章类别
 router.get('/admin/category/list', (req, res) => {
     db(`SELECT * FROM categories`, (err, data) => {
         if (err) return res.send({ code: 400, msg: '获取失败' })
         res.send({ code: 200, msg: '获取成功', data: data })
     })
 })


 //新增文章类别
 router.post('/admin/category/add', (req, res) => {
     const { name, slug } = req.body
         //  console.log({ name, slug })
     db(`INSERT INTO categories SET name=${name},slug=${slug}`, (err, data) => {
         if (err) return res.send({ code: 400, msg: '增加失败' })
         res.send({ code: 200, msg: '创建成功' })
     })
 })


 //根据id查询指定文章类别
 router.get('/admin/category/search', (req, res) => {
         const { id } = req.query
             //  console.log(id)
         db(`SELECT * FROM categories WHERE id=${id}`, (err, data) => {
             if (err || data.length === 0) return res.send({ code: 400, msg: '查询失败，未获取到ID值' })
                 //  console.log(data)
             res.send({ code: 200, msg: '获取成功', data: data })

         })
     })
     //根据id查询指定文章类别第二种方式
 router.get('/admin/category/search/:id', (req, res) => {
     const { id } = req.params
         //  console.log(id)
     db(`SELECT * FROM categories WHERE id=${id}`, (err, data) => {
         if (err || data.length === 0) return res.send({ code: 400, msg: '查询失败，未获取到ID值' })
             //  console.log(data)
         res.send({ code: 200, msg: '获取成功', data: data })

     })
 })


 //编辑文章类别
 router.post('/admin/category/edit', (req, res) => {
     const { id, name, slug } = req.body
     db(`UPDATE categories SET name='${name}',slug='${slug}' WHERE id=${id}`, (err, data) => {
         console.log(data)
         if (err || data.affectedRows === 0) return res.send({ code: 400, msg: '编辑失败' })
         res.send({ code: 200, msg: '编辑成功' })
     })
 })


 //删除文章类别
 router.post('/admin/category/delete', (req, res) => {
     const { id } = req.body
         //  console.log(id)
     db(`DELETE FROM categories WHERE id=${id}`, (err, data) => {
         if (err || data.affectedRows === 0) return res.send({ code: 400, msg: '删除失败' })
         res.send({ code: 200, msg: '删除成功' })

     })
 })




 module.exports = router